package org.finalministry.web;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.finalministry.database.FinalministryDatabase;

public class StartWebServerGui extends JFrame {

	private static final long serialVersionUID = -5488944274766895002L;

	private FinalministryDatabase database;

	public StartWebServerGui(FinalministryDatabase database) {
		this.database = database;
		this.setTitle("Finalministry Version 2.0 WebServer");
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		JLabel welcome = new JLabel(
				"<html><div style=\"margin: 100px 50px;\"><h2>Welcome</h2><p>Finalministry works now locally on your machine. Click on the screen in order to open it in your browser.</p></div>");
		// add(welcome);

		JButton startFinalministry = new JButton(
				"<html><div style=\"margin: 100px 50px;\"><h2>Welcome</h2><p>Finalministry works now locally on your machine. Click on the button below in order to open it in your browser.</p></div>");
		startFinalministry.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				try {

					File local = new File("");
					String localPath = local.getAbsolutePath();
					System.out.println("file://" + localPath + "/finalministry.html");
					Desktop.getDesktop().browse(new URL("file://" + localPath + "/web/finalministry.htm").toURI());
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		add(startFinalministry);

		// Add a Window Listener for the Closing Event
		addWindowClosingEventListener();

		this.setBounds(200, 200, 400, 300);
		this.setVisible(true);
	}

	public void addWindowClosingEventListener() {
		addWindowListener(new java.awt.event.WindowAdapter() {
			@Override
			public void windowClosing(java.awt.event.WindowEvent windowEvent) {
				exit();
			}
		});
	}

	public void exit() {
		System.out.println("Closing Finalministry Desktop ... good bye!");
		database.stopServer();
		System.exit(0);
	}
}
